import React, { useState, useCallback, useEffect } from 'react'
import { Table, Button, Divider, Input, Drawer, } from 'antd'
import { PlusOutlined } from '@ant-design/icons';
import New from './new'
import { fieldType } from '../setting'

import '../index.less'

export default function ResponseField(props: any) {

  const [dataSource, setDataSource] = useState<any>([]);
  const [newVisible, setNewVisible] = useState(false);

  useEffect(() => {
    const { onDataChange } = props;
    onDataChange(dataSource);
  }, [dataSource]);

  const columns = [{
    title: "名称",
    dataIndex: "name",
    render: (value: any, record: any, index: any) => {
      if ([null, undefined, "normal"].includes(record._status)) {
        return value;
      }
      return (
        <Input className="error" />
      )
    }
  }, {
    title: "类型",
    dataIndex: "type",
    render: (value: any) => {
      return fieldType[value].text;
    }
  }, {
    title: "操作",
    dataIndex: "id",
    width: 120,
    render: (value: any, record: any, index: any) => {
      if ([null, undefined, "normal"].includes(record._status)) {
        return (
          <>
            <a onClick={() => { editRow(index) }}>编辑</a>
            <Divider type="vertical" />
            <a>删除</a>
          </>
        )
      }
      return (
        <>
          <a>保存</a>
          <Divider type="vertical" />
          <a>取消</a>
        </>
      )
    }
  }]

  const editRow = useCallback(
    (index: any) => {
      const record = dataSource[index];
      record._status = "edit";
      setDataSource([...dataSource]);
    },
    [dataSource],
  )

  function add() {
    setNewVisible(true);
  }

  function close() {
    setNewVisible(false);
  }

  function saveRow(data: any) {
    if (!data.id) {
      data.id = new Date().getTime();
      setDataSource((prev: any) => ([...prev, data]));
    }
    setNewVisible(false);
  }

  return (
    <div className="field">
      <Button type="primary" onClick={add} icon={<PlusOutlined />}>添加</Button>
      <Table
        dataSource={dataSource}
        columns={columns}
        rowKey="id"
        pagination={false}
      />
      <Drawer
        visible={newVisible}
        title="新建响应参数"
        width="50vw"
        onClose={close}
        destroyOnClose
      >
        <New onSave={saveRow} />
      </Drawer>
    </div>

  )
}